import json

from django import http
from django.shortcuts import render

# Create your views here.
from django.views import View
from django_redis import get_redis_connection

from apps.goods.models import SKU
from apps.goods.utils import CookieSecret
from utils.response_code import RETCODE


class CartsView(View):
    # 将商品存在购物车
    def post(self,request):
        json_dict=json.loads(request.body.decode())
        sku_id=json_dict.get('sku_id')
        count=json_dict.get('count')
        selected=json_dict.get('selected',True)
        user=request.user

        cookie_dict={}

        if user.is_authenticated:

            #如果登陆存redis
            redis_client=get_redis_connection('carts')

            #1这个商品存不存在
            #2这个用户的数据在redis里存不存在

            redis_carts=redis_client.hgetall(str('carts_%d' % user.id).encode())

            if str(sku_id).encode() in redis_carts:

                count1=json.loads((redis_carts[str(sku_id).encode()]).decode())['count']

                count1+=count

                cart_dict={'count':count1,'selected':selected}
                redis_client.hset('carts_%d' % user.id, sku_id, json.dumps(cart_dict))
            else:
                cart_dict = {'count': count, 'selected': selected}
                redis_client.hset('carts_%d' %user.id,sku_id,json.dumps(cart_dict))
            return http.JsonResponse({'code': RETCODE.OK, 'errmsg': '添加购物车成功'})
        else:
            #如果未登录存cookies

            # 用户未登录，操作cookie购物车
            cart_str = request.COOKIES.get('carts')
            # 如果用户操作过cookie购物车
            if cart_str:
                # 解密出明文
                cart_dict = CookieSecret.loads(cart_str)
            else:  # 用户从没有操作过cookie购物车
                cart_dict = {}

            # 判断要加入购物车的商品是否已经在购物车中,如有相同商品，累加求和，反之，直接赋值
            if sku_id in cart_dict:
                # 累加求和
                origin_count = cart_dict[sku_id]['count']
                count += origin_count
            cart_dict[sku_id] = {
                'count': count,
                'selected': selected
            }
            # 转成密文
            cookie_cart_str = CookieSecret.dumps(cart_dict)

            # 创建响应对象
            response = http.JsonResponse({'code': RETCODE.OK, 'errmsg': '添加购物车成功'})
            # 响应结果并将购物车数据写入到cookie
            response.set_cookie('carts', cookie_cart_str, max_age=24 * 30 * 3600)
            return response


    # 展示购物车页面
    def get(self,request):
        user=request.user

        cart_skus=[]
        if user.is_authenticated:
            #如果登陆从redis里取
            redis_client=get_redis_connection('carts')
            carts_dict=redis_client.hgetall('carts_%d'%user.id)


            for key,value in carts_dict.items():
                sku_id=int(key.decode())
                carts_data=json.loads(value.decode())
                sku=SKU.objects.get(id=sku_id)
                cart_skus.append({
                        'id': sku.id,
                        'name': sku.name,
                        'count': carts_data.get('count'),
                        'selected': str(carts_data.get('selected')),  # 将True，转'True'，方便json解析
                        'default_image_url': sku.default_image.url,
                        'price': str(sku.price),  # 从Decimal('10.2')中取出'10.2'，方便json解析
                        'amount': str(sku.price * carts_data.get('count')),
                    })
        #未登录从cookie取
        else:
            cookie_data=request.COOKIES.get('carts')
            if not cookie_data:
                cart_skus = []
            try:
                cookie_data=CookieSecret.loads(cookie_data)
            except:
                cookie_data={}
            for key,value in cookie_data.items():
                sku=SKU.objects.get(id=key)
                cart_skus.append({
                    'id': sku.id,
                    'name': sku.name,
                    'count': value.get('count'),
                    'selected': str(value.get('selected')),  # 将True，转'True'，方便json解析
                    'default_image_url': sku.default_image.url,
                    'price': str(sku.price),  # 从Decimal('10.2')中取出'10.2'，方便json解析
                    'amount': str(sku.price * value.get('count')),
                })
        context={
            'cart_skus':cart_skus
        }

        return render(request,'cart.html',context)

    # 修改购物车（覆盖数据）
    def put(self,request):
        request_data=json.loads(request.body.decode())
        sku_id=request_data.get('sku_id')
        count=request_data.get('count')
        selected=request_data.get('selected')
        cart_sku=[]
        try:
            sku=SKU.objects.get(id=sku_id)
        except:
            return http.HttpResponseForbidden('不存在此商品')

        # 校验数据是否符合格式
        # 判断登录
        user=request.user

        if user.is_authenticated:

            #登陆改redis
            redis_carts=get_redis_connection('carts')
            carts_data={'count':count,'selected':selected}
            redis_carts.hset('carts_%d'% user.id,sku_id,json.dumps(carts_data))
            cart_sku = {
            'id': sku_id,
            'count': count,
            'selected': selected,
            'name': sku.name,
            'default_image_url': sku.default_image.url,
            'price': sku.price,
            'amount': sku.price * count,
            }


        #未登录改cookie
        else:

            cookie_data=request.COOKIES.get('carts')

            if cookie_data:
                # 将cart_str转成bytes,再将bytes转成base64的bytes,最后将bytes转字典
                cart_dict = CookieSecret.loads(cookie_data)
            else:
                cart_dict = {}

            cart_dict[sku_id]={'count':count,'selected':selected}

            cart_dict=CookieSecret.dumps(cart_dict)

        response = http.JsonResponse({'code': RETCODE.OK, 'errmsg': '修改购物车成功', 'cart_sku': cart_sku})
        if not user.is_authenticated:


            response.set_cookie('carts', cart_dict, max_age=14 * 24 * 3600)
            return response
        return response
    #删除购物车数据
    def delete(self,request):
        sku_id=json.loads(request.body.decode()).get('sku_id')
        user=request.user
        try:
            sku = SKU.objects.get(id=sku_id)
        except:
            return http.HttpResponseForbidden('不存在此商品')
        if user.is_authenticated:
            redis_client=get_redis_connection('carts')

            redis_client.hdel('carts_%d'% user.id,sku_id)

            return http.JsonResponse({'code': RETCODE.OK, 'errmsg': '删除购物车成功'})
        else:
            cookie_data=request.COOKIES.get('carts')
            if not cookie_data:
                cookie_data={}
            cookie_data=CookieSecret.loads(cookie_data)
            response=http.JsonResponse({'code': RETCODE.OK, 'errmsg': '删除购物车成功'})
            if sku_id in cookie_data.keys():
                del cookie_data[sku_id]
                response.set_cookie('carts',CookieSecret.dumps(cookie_data),max_age=14*24*3600)
                return response
            else:
                return http.HttpResponseForbidden('不存在该商品')


class CartsSelectAllView(View):
    def put(self,request):
        selected=json.loads(request.body.decode()).get('selected')
        user=request.user
        # 判断是否登录
        if user.is_authenticated:
            #登录则修改redis
            redis_client=get_redis_connection('carts')
            redis_data=redis_client.hgetall('user_%d' %user.id)
            for key,value in redis_data:
                sku_id=int(key.decode())
                sku_dict=value.decode()
                redis_data[sku_id]['selected']=selected
            return http.JsonResponse({'code': RETCODE.OK, 'errmsg': '全选购物车成功'})
        else:
            #修改cookies
            cookies_data=request.COOKIES.get('carts')
            cookies_data=CookieSecret.loads(cookies_data)

            for value in cookies_data:

                cookies_data[value]['selected']=selected
            response=http.JsonResponse({'code': RETCODE.OK, 'errmsg': '全选购物车成功'})
            response.set_cookie('carts',CookieSecret.dumps(cookies_data),max_age=14*24*3600)
            return response



class CartsSimpleView(View):
    def get(self,request):
        user=request.user
        cart_skus=[]
        if user.is_authenticated:
            # 登录
            redis_client=get_redis_connection('carts')
            redis_data=redis_client.hgetall('carts_%d' %user.id)
            for key,value in redis_data.items():
                sku_id=int(key.decode())
                values=json.loads(value.decode())
                sku=SKU.objects.get(id=sku_id)

                cart_skus.append({
                    'id':sku.id,
                    'name':sku.name,
                    'count':values.get(sku_id),
                    'default_image_url':sku.default_image.url
                })

        #未登录
        else:
            cart_skus=[]
            cookie_data=request.COOKIES.get('carts')
            if not cookie_data:
                cart_skus = []
            else:
                cookie_data=CookieSecret.loads(cookie_data)


                for key,value in cookie_data.items():
                        sku=SKU.objects.get(id=key)
                        cart_skus.append({
                            'id':sku.id,
                            'name':sku.name,
                            'count':value['count'],
                            'default_image_url':sku.default_image.url
                        })

        return http.JsonResponse({'code':RETCODE.OK, 'errmsg':'OK', 'cart_skus':cart_skus})